﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using log4net;

namespace DeployHelper.Logic
{
	public delegate void TaskFinishedEventHandler(object sender,
	                                              EventArgs args);

	public class TaskProcessor
	{
		public static readonly ILog logger = LogManager.GetLogger(typeof (TaskProcessor));

		private IEnumerable<XElement> tasks;


		public TaskProcessor(XDocument document)
		{
			this.tasks = document.Element("tasks").Elements("task");
		}


		public event TaskFinishedEventHandler TaskFinished;


		private void OnTaskFinished(EventArgs args)
		{
			TaskFinishedEventHandler finished = this.TaskFinished;
			if (finished != null) {
				finished(this, args);
			}
		}


		public void Execute(IEnumerable<string> selectedTasks)
		{
			foreach (var taskName in selectedTasks) {
				logger.Info("Processing task: " + taskName);

				var task = (from element in this.tasks
				            where element.Attribute("name").Value == taskName
				            select element).First();

				foreach (var copyFromDirElement in task.Element("source").Element("directories").Elements("directory")) {
					logger.Debug("Source directory " + copyFromDirElement.Value);

					DirectoryInfo dir = new DirectoryInfo(copyFromDirElement.Value);
					List<FileInfo> filesToCopy = new List<FileInfo>();

					var extensions = task.Element("source").Element("extensions").Elements("extension");

					foreach (var element in extensions) {
						filesToCopy.AddRange(dir.GetFiles("*." + element.Value));
					}

					foreach (var file in filesToCopy) {
						foreach (var element in task.Element("destination").Element("directories").Elements("directory")) {
							DirectoryInfo copyToDir = new DirectoryInfo(element.Value);
							string destinationName = string.Format("{0}\\{1}", copyToDir.FullName, file.Name);
							logger.Debug("Full destination file name is " + destinationName);
							File.Copy(file.FullName, destinationName, true);
						}
					}
				}

				logger.InfoFormat("Completed task: {0}.", taskName);

				this.OnTaskFinished(EventArgs.Empty);
			}

			logger.Info("Completed all the tasks.");
		}
	}
}